'use strict';

/**
 * @ngdoc service
 * @name jgappApp.loginService
 * @description
 * # loginService
 * Service in the jgappApp.
 */
angular.module('jgappApp')
  .service('loginService', function ($http, $timeout, openApi, $window, mdfive, $q) {
    // AngularJS will instantiate a singleton by calling "new" on this function
    var loginService = {};
    loginService.login = function () {
      var defer = $q.defer();
      var clientType = 1
      if (navigator.userAgent.match(/(Android)/)) {
        clientType = 1; //android
      } else if (navigator.userAgent.match(/(iPad|iPhone)/)) {
        clientType = 2; //ios
      }
      var userinfo = JSON.parse($window.localStorage.getItem("userinfo")) || {};
      if (!userinfo.userName) {
        $timeout(function () {
          defer.resolve(0)
        }, 10);
        return defer.promise;;
      }
      var params = {
        clientType: clientType,
        passWord: mdfive(userinfo.passWord),
        userName: encodeURI(userinfo.userName),
        accountName: encodeURI(userinfo.accountName)
      };
      $http.post(openApi.login, params).success(function (data) {
        if (data.success && data.result) {
          defer.resolve(data.result)
        } else {
          defer.resolve(0)
        }
      })
      return defer.promise;
    };
    loginService.checkExpired = function () {
      var defer = $q.defer();
      $http.post(openApi.checkSession).success(function (data) {
        defer.resolve(data.result)
      })
      return defer.promise;
    };
    return loginService
  });
